package com.kkshop.database;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.kkshop.utility.ApplicationContextConstants;

public class Main {

    private static final String FILE = "file";
    
    public static void main(String[] args) {
        Map<String, String> arguments = new HashMap<String, String>();
        arguments.put(FILE, null);

        for(int index = 0; index < args.length; index++) {
            if (args[index].startsWith("-")) {
                String arg = args[index].substring(1);
                if (arguments.containsKey(arg) && (index + 1) < args.length && !args[index + 1].startsWith("-")) {
                    arguments.put(arg, args[index+1]);
                    index += 2;
                } else {
                    index += 1;
                }
            } else {
                index += 1;
            }            
        }

        if (arguments.containsValue(null)) {
            printUsage();
            System.exit(1);
            return;
        }

        try {
            AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(ApplicationContextConstants.APPLICATION_CONTEXT_LOADER_PATTERN);
            DataSource dataSource = (DataSource) applicationContext.getBean(ApplicationContextConstants.DATA_SOURCE, DataSource.class);
            Connection connection = dataSource.getConnection();
            try {
                create(connection, arguments.get(FILE));
            } finally {
                connection.close();
            }
        } catch (IOException e) {
            System.err.println("IOException " + e.getMessage());
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("SQLException " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void create(Connection connection, String definitionFileName) throws IOException, SQLException {
        List<String> sqlStatements = readStatementsFromFile(definitionFileName);
        Statement statement = connection.createStatement();
        for (String sqlStatement : sqlStatements) {
            statement.execute(sqlStatement);
        }
    }

    private static List<String> readStatementsFromFile(String fileName) throws IOException, SQLException {
        List<String> result = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            line = line.trim();
            if (line.equals("") || line.startsWith("--")) {
                continue;
            } else if (line.endsWith(";")) {
                sb.append(line.substring(0, line.length()-1));
                result.add(sb.toString());
                sb.setLength(0);
            } else {
                sb.append(line);
                sb.append(" ");
            }
        }
        br.close();
        return result;
    }

    private static void printUsage() {
        System.out.println("Usage: java -jar kkshop-database.jar -file 'file'");
    }
}
